package qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCodeWriter {
    private QRCodeWriter() {
    }

    public static void createQRCode(String contents, String fileName) throws WriterException, IOException {
        // 配置参数对象
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 30%容错
        hints.put(EncodeHintType.MARGIN, 2); // 边距像素

        // 生成BitMatrix
        BitMatrix matrix = new com.google.zxing.qrcode.QRCodeWriter().encode(
                contents,
                BarcodeFormat.QR_CODE,
                300, 300, hints);

        // 渲染为图片
        BufferedImage img = MatrixToImageWriter.toBufferedImage(matrix);
        ImageIO.write(img, "png", new File(fileName + ".png"));
    }
}
